package org.linlinjava.litemall.wx.web;

import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

import static org.linlinjava.litemall.wx.util.WxResponseCode.GOODS_UNSHELVE;

@RestController
@RequestMapping("/wx/cart")
public class WxCartController {

    @Autowired
    CartService cartService;

    @Autowired
    LitemallGoodsService litemallGoodsService;

    @Autowired
    LitemallGoodsProductService litemallGoodsProductService;

    @Autowired
    LitemallAddressService litemallAddressService;

    @Autowired
    LitemallCouponUserService litemallCouponUserService;

    @Autowired
    private LitemallGrouponRulesService grouponRulesService;

    @Autowired
    private LitemallCouponService couponService;

    @Autowired
    private LitemallCouponUserService couponUserService;

    @Autowired
    private CouponVerifyService couponVerifyService;


    /***
     *
     * 直接购买商品 添加购物车
     * 判断是否登陆
     * 判断商品库存是否足够
     * 判断是否存在规格
     * */
    @PostMapping("/fastadd")
    public Object fastadd(@LoginUser Integer userId, @RequestBody LitemallCart cart){
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        LitemallGoods goods = litemallGoodsService.findById(cart.getGoodsId());
        if(!goods.getIsOnSale() || goods ==null){
            return ResponseUtil.fail(GOODS_UNSHELVE, "商品已下架");
        }
        LitemallGoodsProduct product = litemallGoodsProductService.findProductById(cart.getProductId());
        cart.setGoodsName(goods.getName());
        cart.setGoodsSn(goods.getGoodsSn());
        if(product != null )
        {
            cart.setProductId(product.getId());
        }
        cart.setSpecifications(product.getSpecifications());
        cart.setChecked(true);
        cart.setPicUrl(goods.getPicUrl());
        cart.setAddTime(new Date());
        cart.setDeleted(false);
        cart.setUserId(userId);
        cart.setPrice(goods.getRetailPrice());
        LitemallCart cart1 = cartService.litemallCartAdd(cart);
        return ResponseUtil.ok(cart1.getId());
    }

    @GetMapping("/checkout")
    public Object checkout(@LoginUser Integer userId,Integer cartId,Integer addressId,Integer couponId,Integer grouponRulesId){
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        LitemallAddress checkedAddress = null;
        if (addressId == null || addressId.equals(0)) {
            checkedAddress = litemallAddressService.findDefault(userId);
            // 如果仍然没有地址，则是没有收获地址
            // 返回一个空的地址id=0，这样前端则会提醒添加地址
            if (checkedAddress == null) {
                checkedAddress = new LitemallAddress();
                checkedAddress.setId(0);
                addressId = 0;
            } else {
                addressId = checkedAddress.getId();
            }

        } else {
            checkedAddress = litemallAddressService.query(userId, addressId);
            // 如果null, 则报错
            if (checkedAddress == null) {
                return ResponseUtil.badArgumentValue();
            }
        }

        //获取购物车信息
        List<LitemallCart> checkedGoodsList = new ArrayList<>();
        if(cartId == 0){
            checkedGoodsList = cartService.showCart(userId);
        }else {
            LitemallCart cart = cartService.getLitemallCart(userId, cartId);
            checkedGoodsList.add(cart);
        }
        if(checkedGoodsList.size() < 0){
            return ResponseUtil.badArgumentValue();
        }
        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        for (int i = 0; i < checkedGoodsList.size(); i++) {
            LitemallCart litemallCart = checkedGoodsList.get(i);
            checkedGoodsPrice = litemallCart.getPrice().multiply(new BigDecimal(litemallCart.getNumber()));     ;
        }

        // 计算优惠券可用情况
        BigDecimal tmpCouponPrice = new BigDecimal(0.00);
        Integer tmpCouponId = 0;
        int tmpCouponLength = 0;
        List<LitemallCouponUser> litemallCouponUsers = litemallCouponUserService.queryAll(userId);
        for (int i = 0; i < litemallCouponUsers.size(); i++) {
            LitemallCouponUser litemallCouponUser =  litemallCouponUsers.get(i);
            LitemallCoupon coupon = couponVerifyService.checkCoupon(userId, litemallCouponUser.getCouponId(), checkedGoodsPrice);
            if(coupon == null){
                continue;
            }
            tmpCouponLength++;
            if(tmpCouponPrice.compareTo(coupon.getDiscount()) == -1){
                tmpCouponPrice = coupon.getDiscount();
                tmpCouponId = coupon.getId();
            }
        }

        // 获取优惠券减免金额，优惠券可用数量
        int availableCouponLength = tmpCouponLength;
        BigDecimal couponPrice = new BigDecimal(0);
        // 这里存在三种情况
        // 1. 用户不想使用优惠券，则不处理
        // 2. 用户想自动使用优惠券，则选择合适优惠券
        // 3. 用户已选择优惠券，则测试优惠券是否合适
        if (couponId == null || couponId.equals(-1)){
            couponId = -1;
        }
        else if (couponId.equals(0)) {
            couponPrice = tmpCouponPrice;
            couponId = tmpCouponId;
        }
        else {
            LitemallCoupon coupon = couponVerifyService.checkCoupon(userId, couponId, checkedGoodsPrice);
            // 用户选择的优惠券有问题，则选择合适优惠券，否则使用用户选择的优惠券
            if(coupon == null){
                couponPrice = tmpCouponPrice;
                couponId = tmpCouponId;
            }
            else {
                couponPrice = coupon.getDiscount();
            }
        }


        // 根据订单商品总价计算运费，满88则免运费，否则8元；
        BigDecimal freightPrice = new BigDecimal(0.00);
        if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
            freightPrice = SystemConfig.getFreight();
        }
        // 可以使用的其他钱，例如用户积分
        BigDecimal integralPrice = new BigDecimal(0.00);
        // 订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal(0.00));

        BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);


        Map<String, Object> data = new HashMap<>();
        data.put("addressId", addressId);
        data.put("couponId", couponId);
        data.put("cartId", cartId);
        data.put("grouponRulesId", grouponRulesId);
        data.put("grouponPrice", 0);
        data.put("checkedAddress", checkedAddress);
        data.put("availableCouponLength", availableCouponLength);
        data.put("goodsTotalPrice", checkedGoodsPrice);
        data.put("freightPrice", freightPrice);
        data.put("couponPrice", couponPrice);
        data.put("orderTotalPrice", orderTotalPrice);
        data.put("actualPrice", actualPrice);
        data.put("checkedGoodsList", checkedGoodsList);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/add")
    public Object add(@LoginUser Integer userId, HttpServletRequest request, HttpServletResponse response
                        , @RequestBody LitemallCart cart){
        //判断是否上架
        LitemallGoods goods = litemallGoodsService.findById(cart.getGoodsId());
        if(!goods.getIsOnSale()){
            return ResponseUtil.fail(510,"该商品已下架");
        }
        if(cart.getProductId() == null){
            return ResponseUtil.fail(509,"库存不足");
        }
        //判断库存是否充足
        LitemallGoodsProduct product = litemallGoodsProductService.findProductById(cart.getProductId());
        if(product.getDeleted() || product.getNumber() < cart.getNumber()){
            return ResponseUtil.fail(509,"库存不足");
        }
        //判断是否登陆
        if(userId != null){
            cart.setUserId(userId);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName((goods.getName()));
            cart.setPicUrl(goods.getPicUrl());
            cart.setPrice(product.getPrice());
            cart.setSpecifications(product.getSpecifications());
            cart.setChecked(false);
            cart.setAddTime(new Date());
            cartService.addCart(cart,product);
            return ResponseUtil.ok(cart.getNumber());
        }
        return ResponseUtil.unlogin();
    }



    @GetMapping("/index")
    public Object index(@LoginUser Integer userId){
        //定义总计
        double total = 0;
        //返回购物车列表与总计
        Map<String,Object> map = new HashMap<>();
        //判断是否登陆    未登录取cookie数据    登陆取redis数据
        if(userId == null){
            return ResponseUtil.badArgument();
        }
        //已登陆
        List<LitemallCart> litemallCarts = cartService.showCart(userId);

        for (LitemallCart cart : litemallCarts) {
            BigDecimal num = new BigDecimal(cart.getNumber());
            if(cart.getPrice() != null && cart.getChecked()) {
                total += cart.getPrice().multiply(num).doubleValue();
            }
        }

        map.put("cartList", litemallCarts);
        map.put("cartTotal", total);
        return ResponseUtil.ok(map);
    }


    /**
     * 如果原来没有勾选，则设置勾选状态；如果商品已经勾选，则设置非勾选状态。
     */
    @PostMapping("/checked")
    public Object checked(@LoginUser Integer userId, @RequestBody String body){
        //是否登陆
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        //是否有参数
        if(body == null){
            return ResponseUtil.badArgument();
        }
        List<Integer> productIds = JacksonUtil.parseIntegerList(body, "productIds");
        if (productIds == null) {
            return ResponseUtil.badArgument();
        }
        Integer isChecked = JacksonUtil.parseInteger(body, "isChecked");
        if(isChecked == null){
            return ResponseUtil.badArgument();
        }
        boolean flag = (isChecked == 1);
        cartService.updateIsChecked(userId,productIds,flag);
        return index(userId);
    }

    /**
     * 更新购物车商品
     * */
    @PostMapping("/update")
    public Object updateCart(@LoginUser Integer userId, @RequestBody LitemallCart cart){
        LitemallGoodsProduct product = litemallGoodsProductService.findProductById(cart.getProductId());
        if(product.getDeleted() || product.getNumber() < cart.getNumber()){
            return ResponseUtil.fail(509,"库存不足");
        }
        cartService.updateCart(userId,cart);
        return index(userId);
    }

    /**
     * 删除购物车的商品
     * */
    @PostMapping("/delete")
    public Object delete(@LoginUser Integer userId, @RequestBody String body){
        List<Integer> productIds = JacksonUtil.parseIntegerList(body,"productIds");
        if(userId != null){
            boolean b = cartService.deleteCart(userId, productIds);
            if(b){
                return index(userId);
            }
        }
        return ResponseUtil.isNull();
    }

    /**
     * 获取购物车商品件数
     * */
    @GetMapping("/goodscount")
    public Object goodscount(){
        return null;
    }







}
